package org.zebra.web.advice;

import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.zebra.common.core.BaseResponseBodyAdviceChain;

import java.util.Objects;

/**
 * 主要用于日志输出结果
 *
 * @author zhanghongbin
 */
public class LogNotVoidResponseBodyAdviceChain extends BaseResponseBodyAdviceChain {

    @Override
    public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {
        return true;
    }

    @Override
    public Object beforeBodyWrite(
            Object body,
            MethodParameter methodParameter,
            MediaType mediaType,
            Class<? extends HttpMessageConverter<?>> clazz,
            ServerHttpRequest serverHttpRequest,
            ServerHttpResponse serverHttpResponse) {
        // ThreadLocalUtil.$get().set("$result", body);
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        Objects.requireNonNull(requestAttributes).setAttribute("$result", body, RequestAttributes.SCOPE_REQUEST);
        if (this.baseResponseBodyAdviceChain != null) {
            return this.baseResponseBodyAdviceChain.beforeBodyWrite(
                    body, methodParameter, mediaType, clazz, serverHttpRequest, serverHttpResponse);
        }
        return body;
    }
}
